package com.abso.sunlight.explorer.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.handlers.HandlerUtil;

import com.abso.sunlight.api.SunlightException;
import com.abso.sunlight.explorer.CongressExplorerPlugin;
import com.abso.sunlight.explorer.LegislatorSearch;
import com.abso.sunlight.explorer.SelectionUtils;
import com.abso.sunlight.explorer.dialogs.SaveLegislatorSearchDialog;
import com.abso.sunlight.explorer.viewers.ExplorerTreeNode;

/**
 * Renames a legislator's search.
 */
public class RenameLegislatorSearchHandler extends AbstractHandler implements IHandler {

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent)
     */
    public Object execute(ExecutionEvent event) throws ExecutionException {

        /* retrieves the selected search */
        ISelection sel = HandlerUtil.getCurrentSelection(event);
        ExplorerTreeNode node = SelectionUtils.getSelectedExplorerTreeNode(sel, true);
        if (node != null) {
            LegislatorSearch search = ((LegislatorSearch) node.getData());

            /* asks for a new name */
            SaveLegislatorSearchDialog saveDialog = new SaveLegislatorSearchDialog(HandlerUtil.getActiveShell(event), search.getName());
            if (saveDialog.open() == Window.OK) {
                try {

                    /* renames the search */
                    CongressExplorerPlugin.getSearchManager().renameSearch(search, saveDialog.getSearchName());
                } catch (SunlightException e) {
                    ExecutionException e2 = new ExecutionException("Unable to rename", e);
                    ErrorDialog.openError(HandlerUtil.getActiveShell(event), "Error", e2.getMessage(), new Status(IStatus.ERROR,
                            CongressExplorerPlugin.PLUGIN_ID, e.getMessage(), e));
                    throw e2;
                }
            }
        }
        return null;
    }

}
